import pymysql
from python_baway.common.xcommon import sep


class MysqlHelper(object):

    def __init__(self, host, user, password, database, charset, port=3306):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset
        self.port = port
        self.conn = None
        self.cursor = None

    def connect(self):
        if self.conn is not None:
            return

        self.conn = pymysql.connect(host=self.host,
                                    port=self.port,
                                    user=self.user,
                                    password=self.password,
                                    database=self.database,
                                    charset=self.charset)
        self.cursor = self.conn.cursor()

    def close(self):
        if self.conn is None:
            return
        self.cursor.close()
        self.conn.close()
        self.cursor = None
        self.conn = None

    def query(self, xsql):
        self.connect()
        sep(xsql)
        xrows_cnt = self.cursor.execute(xsql)
        xrows = self.cursor.fetchall()
        return xrows, xrows_cnt

    def exec(self, xsql):
        self.connect()
        sep(xsql)
        xrows_cnt = self.cursor.execute(xsql)
        return xrows_cnt

    def commit(self):
        self.conn.commit()